package com.sky.control;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@Slf4j
@RequestMapping("/admin/common")
@Tag(name="通用接口")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/uploadfile")
    @Operation(summary = "文件上传")
    public Result<String> uploadFile(MultipartFile file){
        log.info("文件上传：{}",file);

        try {
            //原始文件名
            String originalFileName=file.getOriginalFilename();
            //截取原始文件的类型 后缀名 xx.png
            String extension=originalFileName.substring(originalFileName.lastIndexOf("."));
            //构造新文件名
            String objectName= UUID.randomUUID().toString()+extension;
            //文件的请求路径
            String filePath=aliOssUtil.upload(file.getBytes(),objectName);
            return  Result.success(filePath);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件上传失败：{}",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
